<?php

/////////////////////// 通用函数 ///////////////////////////
class Util
{
    static function make_str_replace($str, $html_filter = true)
    {//字符串替换函数，主要用于替换掉串中不安全字符使其可用于Sql语句中
        //$str = trim( $str );
        //$str = addslashes( $str );
        $str = str_replace("\'", "’", $str);
        $str = str_replace("+", "＋", $str);
        $str = str_replace("*", "＊", $str);
        $str = str_replace("=", "＝", $str);
        $str = str_replace("<", "＜", $str);
        $str = str_replace(">", "＞", $str);
        $str = str_replace("&lt;", "＜", $str);
        $str = str_replace("&gt;", "＞", $str);
        $str = str_replace("&#60;", "＜", $str);
        $str = str_replace("&#62;", "＞", $str);
        $str = str_replace("&", "＆", $str);
        $str = str_replace("&#38;", "＆", $str);
        $str = str_replace("&amp;", "＆", $str);
        $str = str_replace("'", "‘", $str);
        $str = str_replace('"', "“", $str);
        $str = str_replace("SELECT", "ＳＥＬＥＣＴ", $str);
        $str = str_replace("INSERT", "ＩＮＳＥＲＴ", $str);
        $str = str_replace("UPDATE", "ＵＰＤＡＴＥ", $str);
        $str = str_replace("DELETE", "ＤＥＬＥＴＥ", $str);
        $str = str_replace("INTO", "ＩＮＴＯ", $str);
        $str = str_replace("LOAD_FILE", "ＬＯＡＤ＿ＦＩＬＥ", $str);
        $str = str_replace("OUTFILE", "ＯＵＴＦＩＬＥ", $str);
        $str = str_replace("select", "ＳＥＬＥＣＴ", $str);
        $str = str_replace("insert", "ＩＮＳＥＲＴ", $str);
        $str = str_replace("update", "ＵＰＤＡＴＥ", $str);
        $str = str_replace("delete", "ＤＥＬＥＴＥ", $str);
        $str = str_replace("into", "ＩＮＴＯ", $str);
        $str = str_replace("load_file", "ＬＯＡＤ＿ＦＩＬＥ", $str);
        $str = str_replace("outfile", "ＯＵＴＦＩＬＥ", $str);
        $str = str_replace("Select", "ＳＥＬＥＣＴ", $str);
        $str = str_replace("Insert", "ＩＮＳＥＲＴ", $str);
        $str = str_replace("Update", "ＵＰＤＡＴＥ", $str);
        $str = str_replace("Delete", "ＤＥＬＥＴＥ", $str);
        $str = str_replace("Union", "ＵＮＩＯＮ", $str);
        $str = str_replace("Into", "ＩＮＴＯ", $str);
        $str = str_replace("Load_File", "ＬＯＡＤ＿ＦＩＬＥ", $str);
        $str = str_replace("OutFile", "ＯＵＴＦＩＬＥ", $str);
        $str = str_replace("\'", "＼", $str);
        $str = str_replace("\/\*", "＼＼＊", $str);
        $str = str_replace("\*", "＼＊", $str);
        $str = str_replace("\.\.\/", "＼．＼．＼", $str);
        $str = str_replace("\.\/", "＼．＼", $str);
        if ($html_filter) $str = htmlspecialchars($str);
        $str = preg_replace('/[\x00-\x08\x0b\x0c\x0e-\x1f]/', '', $str);
        return $str;
    }

    //针对数字进行排序
    static function array_sort($arr, $keys, $type = 'DESC')
    {
        if (trim($arr) <> "" && trim($keys) <> "")
        {
            foreach ($arr as $key => $row)
            {
                $gettmp[$key] = $row[$keys];
            }
            if ($type == "DESC")
            {
                array_multisort($gettmp, SORT_DESC, $arr);
            }
            else
            {
                array_multisort($gettmp, SORT_ASC, $arr);
            }
        }
        return $arr;
    }

    static function sortmddata($array, $by, $order, $type)
    {//数组排序 $test = sortmddata($strMemo,'CreateTime','DESC','str');
        //$array: the array you want to sort
        //$by: the associative array name that is one level deep
        ////example: name
        //$order: ASC or DESC
        //$type: num or str
        if (trim($array) <> "" && trim($by) <> "" && trim($order) <> "" && trim($type) <> "")
        {
            $sortby = "sort$by"; //This sets up what you are sorting by

            $firstval = current($array); //Pulls over the first array

            $vals = array_keys($firstval); //Grabs the associate Arrays

            foreach ($vals as $init)
            {
                $keyname = "sort$init";
                $$keyname = array();
            }
            //This was strange because I had problems adding
            //Multiple arrays into a variable variable
            //I got it to work by initializing the variable variables as arrays
            //Before I went any further

            foreach ($array as $key => $row)
            {

                foreach ($vals as $names)
                {
                    $keyname = "sort$names";
                    $test = array();
                    $test[$key] = $row[$names];
                    $$keyname = array_merge($$keyname, $test);

                }

            }

            //This will create dynamic mini arrays so that I can perform
            //the array multisort with no problem
            //Notice the temp array... I had to do that because I
            //cannot assign additional array elements to a
            //varaiable variable

            if ($order == "DESC")
            {
                if ($type == "num")
                {
                    array_multisort($$sortby, SORT_DESC, SORT_NUMERIC, $array);
                }
                else
                {
                    array_multisort($$sortby, SORT_DESC, SORT_STRING, $array);
                }
            }
            else
            {
                if ($type == "num")
                {
                    array_multisort($$sortby, SORT_ASC, SORT_NUMERIC, $array);
                }
                else
                {
                    array_multisort($$sortby, SORT_ASC, SORT_STRING, $array);
                }
            }

            //This just goed through and asks the additional arguments
            //What they are doing and are doing variations of
            //the multisort

            return $array;
        }
        else
        {
            return $array;
        }
    }

    //分页计算
    static function page_sum($Total, $pagelist)
    {
        $intSum = 0;
        $intSum = round($Total / $pagelist + 0.49);
        return $intSum;
    }

    //计算两个地点的距离(经纬度)
    static function getdistance($lng1, $lat1, $lng2, $lat2)
    {
        /*
        这里计算一下“上海市延安西路2055弄”到“上海市静安寺”的距离：
        上海市延安西路2055弄 经纬度：31.2014966,121.40233369999998
        上海市静安寺 经纬度：31.22323799999999,121.44552099999998
        则：
        echo getdistance(31.2014966,121.40233369999998,31.22323799999999,121.44552099999998);
        结果为：4970.4248747365 ，约4970米，大约10里路，据我以前经常往返于这两点一线的经验，应该还差不多吧。
        */
        //将角度转为狐度
        $radLat1 = deg2rad($lat1);//deg2rad()函数将角度转换为弧度
        $radLat2 = deg2rad($lat2);
        $radLng1 = deg2rad($lng1);
        $radLng2 = deg2rad($lng2);
        $a = $radLat1 - $radLat2;
        $b = $radLng1 - $radLng2;
        $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137 * 1000;
        return $s;
    }

    //查询配送药店
    static function get_fanwei($YD_JinDu, $YD_WeiDu, $KF_JinDu, $KF_WeiDu, $YD_JinDuXMin, $YD_WeiDuYMin, $YD_JinDuXMax, $YD_WeiDuYMax, $YD_PeiSong)
    {//$YD_JinDu=药店经度, $YD_WeiDu=药店纬度, $KF_JinDu=用户经度, $KF_WeiDu=用户纬度, $YD_JinDuXMin=药店经度最小值, $YD_WeiDuYMin=药店纬度最小值, $YD_JinDuXMax=药店经度最大值, $YD_WeiDuYMax=药店纬度最大值, $YD_PeiSong=配送多少米
        $intstate = 0;    //可以配送
        $getm = Util::getdistance($YD_JinDu, $YD_WeiDu, $KF_JinDu, $KF_WeiDu);
        if ($getm > $YD_PeiSong)
        {
            $intstate = 1;
        }
        if ($intstate == 0)
        {
            if ($KF_JinDu < $YD_JinDuXMin)
            {
                $intstate = 1;
            }
            else if ($KF_JinDu > $YD_JinDuXMax)
            {
                $intstate = 1;
            }
        }
        if ($intstate == 0)
        {
            if ($KF_WeiDu < $YD_WeiDuYMin)
            {
                $intstate = 1;
            }
            else if ($KF_WeiDu > $YD_WeiDuYMax)
            {
                $intstate = 1;
            }
        }
        return $intstate;
    }

    static function showpic($strpicurl, $inttype)
    {//显示图片
        //0=原图;1=160x160;2=116x116;3=100x100;4=60x60
        if ($strpicurl == "")
        {//头像是空
            $strpicurl = "/images/none/" . $inttype . ".gif";
        }
        else
        {
            $strpicurl = str_replace("s", "", $strpicurl);
            $strpicurl = str_replace("S", "", $strpicurl);
            if ($inttype == 1)
            {//1=160x160
                $strpicurl = str_replace(".jpg", "s.jpg", $strpicurl);
            }
            else if ($inttype == 2)
            {//2=116x116
                $strpicurl = str_replace(".jpg", "ss.jpg", $strpicurl);
            }
            else if ($inttype == 3)
            {//3=100x100
                $strpicurl = str_replace(".jpg", "sss.jpg", $strpicurl);
            }
            else if ($inttype == 4)
            {//4=60x60
                $strpicurl = str_replace(".jpg", "ssss.jpg", $strpicurl);
            }
            else if ($inttype == 5)
            {//5=50x50
                $strpicurl = str_replace(".jpg", "sssss.jpg", $strpicurl);
            }
            else if ($inttype == 6)
            {//6=32x32
                $strpicurl = str_replace(".jpg", "ssssss.jpg", $strpicurl);
            }
            else if ($inttype == 7)
            {//7=390x390
                $strpicurl = str_replace(".jpg", "sssssss.jpg", $strpicurl);
            }
        }

        return $strpicurl;
    }


    /**
     *计算某个经纬度的周围某段距离的正方形的四个点
     *
     * @param lng float 经度
     * @param lat float 纬度
     * @param distance float 该点所在圆的半径，该圆与此正方形内切，默认值为0.5千米
     * @return array 正方形的四个点的经纬度坐标
     * //使用此函数计算得到结果后，带入sql查询。
     * $squares = returnSquarePoint($lng, $lat);
     * $info_sql = "select id,locateinfo,lat,lng from `lbs_info` where lat<>0 and lat>{$squares['right-bottom']['lat']} and lat<{$squares['left-top']['lat']} and lng>{$squares['left-top']['lng']} and lng<{$squares['right-bottom']['lng']} ";
     */
    static function returnSquarePoint($lng, $lat, $distance = 0.5)
    {
        define(EARTH_RADIUS, 6371);//地球半径，平均半径为6371km
        $dlng = 2 * asin(sin($distance / (2 * EARTH_RADIUS)) / cos(deg2rad($lat)));
        $dlng = rad2deg($dlng);

        $dlat = $distance / EARTH_RADIUS;
        $dlat = rad2deg($dlat);

        return array(
            'left-top' => array('lat' => $lat + $dlat, 'lng' => $lng - $dlng),
            'right-top' => array('lat' => $lat + $dlat, 'lng' => $lng + $dlng),
            'left-bottom' => array('lat' => $lat - $dlat, 'lng' => $lng - $dlng),
            'right-bottom' => array('lat' => $lat - $dlat, 'lng' => $lng + $dlng)
        );
    }

    static function make_rand($intmin, $intmax)
    {//产生随机数
        $seedarray = microtime();
        $seedstr = split(" ", $seedarray, 5);
        $seed = $seedstr[0] * 100000;
        srand($seed);
        $strmemo = rand($intmin, $intmax);
        return $strmemo;
    }

    static function logpagelogs($inttype, $strpage, $inttime)
    {//记录页面超时记录：inttype：0=表示页面；1=表示SQL语句；strpage=页面名称；inttime=执行时间
        if ($inttype == 1)
        {
            error_log($strpage . ";" . $inttime . ";" . date("Y-m-d H:i:s") . "\n", 3, "/www/htdocs/okwww/apppeisong/logs/SQLOut_" . date("Ymd") . ".txt");
        }
        else if ($inttype == 2)
        {
            error_log($strpage . ";" . $inttime . ";" . date("Y-m-d H:i:s") . "\n", 3, "/www/htdocs/okwww/apppeisong/logs/Data_" . date("Ymd") . ".txt");
        }
        else
        {
            error_log($strpage . ";" . $inttime . ";" . date("Y-m-d H:i:s") . "\n", 3, "/www/htdocs/okwww/apppeisong/logs/PageOut_" . date("Ymd") . ".txt");
        }
    }

    static function send_sms($UserID, $MobileNo, $Memo)
    {//发送短信
        $us = "10690117";
        $ps = "yaoS106";

        $SmsMemo = $Memo . "【快方送药】";
        $SmsMemo = bin2hex(iconv("UTf-8", "GB2312", $SmsMemo));
        $url = "http://101.227.68.49:7891/mt?un=" . $us . "&pw=" . $ps . "&da=" . $MobileNo . "&sm=" . $SmsMemo . "&dc=15&rd=1";
        $re = file_get_contents($url);
        if (strlen($re) > 10)
        {
            Util::update_sms_logs($UserID, $MobileNo, $Memo, 1, $re, '');
            return 1;
        }
        else
        {
            Util::update_sms_logs($UserID, $MobileNo, $Memo, 0, $re, '');
            return 0;
        }
    }

    static function update_sms_logs($UserID, $MobileNo, $Memo, $SendType, $OrderCode, $MK)
    {//记录发送短信
        global $db, $mc;
        $getip = Util::fetch_real_ip();
        $tablename = "kfsy_logs.kf_sms_logs_" . date("Ym");
        $sql = "INSERT INTO " . $tablename . " (UID,MobileNo,OrderCode,Memo,CreateTime,State,IP,MK) VALUES ('" . $UserID . "','" . $MobileNo . "','" . $OrderCode . "','" . $Memo . "',now(),'" . $SendType . "','" . $getip . "','" . $MK . "')";
        $res = DB::insert_db($UserID, $sql);
    }

    static function fetch_real_ip()
    {//获取用户ID
        if (isset($_SERVER["HTTP_X_FORWARDED_FOR"]) && preg_match_all('/(\d{1,3}\.){3}\d{1,3}/s', $_SERVER['HTTP_X_FORWARDED_FOR'], $mat))
        {
            foreach ($mat[0] AS $ip)
            {
                //得到第一个非内网的IP地址
                if (!preg_match("/^(?:10|172\.16|192\.168)\./", $ip))
                {
                    return $ip;
                }
            }
            return $ip;
        }
        elseif (isset($_SERVER["HTTP_FROM"]) && preg_match('/(?:\d{1,3}\.){3}\d{1,3}/', $_SERVER["HTTP_FROM"]))
        {
            return $_SERVER["HTTP_FROM"];
        }
        else
            return $_SERVER['REMOTE_ADDR'];
    }

    //计算时间
    static function make_timeonline($strdate2, $MakeType = 0)
    {
        $intstate = 1;
        $strdate1 = date("Y-m-d H:i:s");
        $get1 = strtotime($strdate1);
        $get2 = strtotime($strdate2);
        $strmemo = "";
        $getsum = $get1 - $get2;    //计算出来单位为秒
        $getyear = substr($strdate2, 0, 4);

        if ($getsum <= 82800)
        {//X小时前
            $strmemo = intval($getsum / 3600);
            if ($strmemo == 0)
            {
                $strmemo = intval($getsum / 60) . "分钟前";
            }
            else
            {
                $strmemo = 100;
            }
        }
        else
        {
            $strmemo = 100;
        }
        return $strmemo;
    }

    //日期单个时间相加减:如加一个月减一个月
    static function data_make_list($data, $maketype, $qty, $type)
    {//日期，操作对像，数量，操作类型加还是减
        $year = substr($data, 0, 4);
        $month = substr($data, 5, 2);
        $day = substr($data, 8, 2);
        $hours = substr($data, 11, 2);
        $minutes = substr($data, 14, 2);
        $seconds = substr($data, 17, 2);
        switch ($maketype)
        {
            case "y":
                if ($type == 0)
                {
                    $timestamp = mktime($hours, $minutes, $seconds, $month, $day, $year + $qty);
                }
                else
                {
                    $timestamp = mktime($hours, $minutes, $seconds, $month, $day, $year - $qty);
                }
                break;
            case "m":
                if ($type == 0)
                {
                    $timestamp = mktime($hours, $minutes, $seconds, $month + $qty, $day, $year);
                }
                else
                {
                    $timestamp = mktime($hours, $minutes, $seconds, $month - $qty, $day, $year);
                }
                break;
            case "d":
                if ($type == 0)
                {
                    $timestamp = mktime($hours, $minutes, $seconds, $month, $day + $qty, $year);
                }
                else
                {
                    $timestamp = mktime($hours, $minutes, $seconds, $month, $day - $qty, $year);
                }
                break;
            case "h":
                if ($type == 0)
                {
                    $timestamp = mktime($hours + $qty, $minutes, $seconds, $month, $day, $year);
                }
                else
                {
                    $timestamp = mktime($hours - $qty, $minutes, $seconds, $month, $day, $year);
                }
                break;
            case "i":
                if ($type == 0)
                {
                    $timestamp = mktime($hours, $minutes + $qty, $seconds, $month, $day, $year);
                }
                else
                {
                    $timestamp = mktime($hours, $minutes - $qty, $seconds, $month, $day, $year);
                }
                break;
            case "s":
                if ($type == 0)
                {
                    $timestamp = mktime($hours, $minutes, $seconds + $qty, $month, $day, $year);
                }
                else
                {
                    $timestamp = mktime($hours, $minutes, $seconds - $qty, $month, $day, $year);
                }
                break;
            default:
                $timestamp = mktime($hours, $minutes, $seconds, $month, $day, $year);
                break;
        }
        $strdate = date("Y", $timestamp) . "-" . date("m", $timestamp) . "-" . date("d", $timestamp) . " " . date("H", $timestamp) . ":" . date("i", $timestamp) . ":" . date("s", $timestamp);

        return $strdate;
    }

    //计算分钟
    static function make_timetofen($strdate2, $intsumfen, $MakeType = 0)
    {
        if ($intsumfen == 0)
        {
            $intsumfen = 60;
        }
        $intstate = 1;
        $strdate1 = date("Y-m-d H:i:s");
        $get1 = strtotime($strdate1);
        $get2 = strtotime($strdate2);
        $strmemo = "";
        $getsum = $get1 - $get2;    //计算出来单位为秒
        //$getyear = substr($strdate2, 0, 4);

        $strmemo = intval($getsum / 60);
        $strmemo = $intsumfen - $strmemo;
        if ($strmemo <= 0)
        {
            $strmemo = 0;
        }
        return $strmemo;
    }

    static function en_key_num_pass($strnum)
    {//加密
        $getw = date("w");
        $getm = date("m");
        $newnum = $getw . $strnum . $getm;
        $getl = strlen($newnum);
        $strmemonew = "";
        for ($i = 1; $i <= $getw; $i++)
        {
            $strmemonew .= substr($newnum, ($getl - $i), 1);
            if ($i == $getw)
            {
                $strmemonew .= substr($newnum, 0, ($getl - $i));
            }
        }
        $getone = Util::make_rand(1, 9);
        if (strlen($strmemonew) < $getone)
        {
            $strnew2 = $getone . substr($strmemonew, 0, $getone) . Util::make_rand(10, 99);
        }
        else
        {
            $strnew2 = $getone . substr($strmemonew, 0, $getone) . Util::make_rand(10, 99) . substr($strmemonew, $getone, 20);
        }
        return $strnew2;
    }

    static function dc_key_num_pass($strnum)
    {//解密
        $getl = strlen($strnum);
        $getone = substr($strnum, 0, 1);
        if ($getl <= ($getone + 2))
        {
            $benum = substr($strnum, 1, ($getl - 3));
        }
        else
        {
            $benum = substr($strnum, 1, $getone) . substr($strnum, ($getone + 3), 20);
        }
        $getw = date("w");
        $getm = date("m");
        $strmemonew = "";
        //$benum = substr($benum,1,30);
        for ($i = 0; $i < $getw; $i++)
        {
            $strmemonew = substr($benum, $i, 1) . $strmemonew;
            if (($i + 1) == $getw)
            {
                $strmemonew .= substr($benum, $getw, 20) . $strmemonew;
            }
        }
        $strl = strlen($strmemonew);
        $strnew2 = substr($strmemonew, 2, ($strl - 4));

        return $strnew2;
    }

    static function unicode_csubstr($str, $start, $len, $intstate = 0)
    {//取字符串中的某一些字符(unicode)
        $stroldmemo = $str;
        $strmemo = "";
        $pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf]";
        $pa .= "[\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|";
        $pa .= "\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|";
        $pa .= "[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
        preg_match_all($pa, $str, $t_string);
        if (count($t_string[0]) - $start > $len)
        {

            $strmemo = join('', array_slice($t_string[0], $start, $len));//."..";
        }
        else
        {
            $strmemo = join('', array_slice($t_string[0], $start, $len));
        }
        if ($intstate == 1 && $stroldmemo <> $strmemo)
        {
            $strmemo .= "...";
        }
        return $strmemo;
    }

    static function get_client_ip()
    {
        if (isset($_SERVER['HTTP_CLIENT_IP']) && !empty($_SERVER['HTTP_CLIENT_IP']))
        {
            return $_SERVER['HTTP_CLIENT_IP'];
        }
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR']))
        {
            return strtok($_SERVER['HTTP_X_FORWARDED_FOR'], ',');
        }
        if (isset($_SERVER['HTTP_PROXY_USER']) && !empty($_SERVER['HTTP_PROXY_USER']))
        {
            return $_SERVER['HTTP_PROXY_USER'];
        }
        if (isset($_SERVER['REMOTE_ADDR']) && !empty($_SERVER['REMOTE_ADDR']))
        {
            return $_SERVER['REMOTE_ADDR'];
        }
        return "0.0.0.0";
    }

    static function generate_code($length = 4)
    {
        return mt_rand(pow(10, ($length - 1)), pow(10, $length) - 1);
    }

    /**
     * 生成UUID 单机使用
     * @access public
     * @return string
     */
    static public function uuid()
    {
        $charid = md5(uniqid(mt_rand(), true));
        $hyphen = chr(45);// "-"
        $uuid = chr(123)// "{"
            . substr($charid, 0, 8) . $hyphen
            . substr($charid, 8, 4) . $hyphen
            . substr($charid, 12, 4) . $hyphen
            . substr($charid, 16, 4) . $hyphen
            . substr($charid, 20, 12)
            . chr(125);// "}"
        return $uuid;
    }

    /**
     * 生成Guid主键
     * @return Boolean
     */
    static public function keyGen()
    {
        return str_replace('-', '', substr(self::uuid(), 1, -1));
    }

    static function del_dir($dir)
    {
        try
        {
            if ($handle = opendir("$dir"))
            {
                while (false !== ($item = readdir($handle)))
                {
                    if ($item != "." && $item != "..")
                    {
                        if (is_dir("$dir/$item"))
                        {
                            self::del_dir("$dir/$item");
                        }
                        else
                        {
                            unlink("$dir/$item");
                        }
                    }
                }
                closedir($handle);
                return rmdir($dir);
            }
        }
        catch (Exception $ex)
        {
            return false;
        }
    }

    static function string_to_int_array($string, $token = '；;')
    {
        $result = array();
        $tok = strtok($string, $token);
        while ($tok !== false)
        {
            if (preg_match('/^[1-9]\d*$/', $tok)) $result[$tok] = 1;
            $tok = strtok($token);
        }
        return array_keys($result);
    }

    static function string_to_string($string, $token = '；;')
    {
        $result = array();
        $tok = strtok($string, $token);
        while ($tok !== false)
        {
            if (!empty($tok))
            {
                $arr = explode(',', str_replace('，', ',', $tok));
                if (count($arr) >= 2 && preg_match('/^(0|[1-9]\d*)$/', $arr[0]) && filter_var($arr[1], FILTER_VALIDATE_URL))
                {
                    $result[] = $arr[0] . ',' . $arr[1];
                }
            }
            $tok = strtok($token);
        }
        return implode(';', $result);
    }

    static function is_ajax()
    {
        return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
    }

    static function csv_export($filename, $header, $content, $columns = array())
    {
        set_time_limit(0);
        header('Content-Type: application/vnd.ms-excel');
        //处理中文文件名
        $agent = $_SERVER["HTTP_USER_AGENT"];
        if (preg_match("/MSIE/", $agent))
        {
            header('Content-Disposition: attachment; filename="' . rawurlencode($filename) . '"');
        }
        else if (preg_match("/Firefox/", $agent))
        {
            header("Content-Disposition: attachment; filename*=\"utf8''" . $filename . '"');
        }
        else
        {
            header('Content-Disposition: attachment; filename="' . $filename . '"');
        }
        header('Cache-Control: max-age=0');
        $fp = fopen('php://output', 'a');

        if ($header)
        {
            foreach ($header as $i => $v)
            {
                $header[$i] = iconv('utf-8', 'gbk', $v);
            }
            fputcsv($fp, $header);
        }
        if ($content)
        {
            $cnt = 0;
            $limit = 10000;

            foreach ($content as $data)
            {
                $cnt++;
                if ($limit == $cnt)
                {
                    ob_flush();
                    flush();
                    $cnt = 0;
                }

                $row = array();
                if ($columns)
                {
                    foreach ($columns as $column)
                    {
                        if (isset($column['formatter']))
                        {
                            $value = $column['formatter']($data[$column['db']], $data);
                        }
                        else
                        {
                            $value = $data[$column['db']];
                        }
                        if (Util::is_excel_bigint($value))
                            $row[] = "=\"" . $value . "\"";
                        else
                            $row[] = iconv('utf-8', 'gbk', $value);
                    }
                }
                else
                {
                    foreach ($data as $value)
                    {
                        if (Util::is_excel_bigint($value))
                            $row[] = "=\"" . $value . "\"";
                        else
                            $row[] = iconv('utf-8', 'gbk', $value);
                    }
                }
                fputcsv($fp, $row);
                unset($row);
            }
        }
        fclose($fp);
    }

    static function is_excel_bigint($value)
    {
        return is_numeric($value) && strlen($value) > 11;
    }

    static function excel_export($filename, $header, $content, $columns = array())
    {
        function get_column_index($row, $col)
        {
            $index = PHPExcel_Cell::stringFromColumnIndex($col);
            return $index . ($row + 1);
        }

        set_time_limit(0);
        ini_set('memory_limit', '512M');

        require dirname(__FILE__) . '/../ghdb/PHPExcel-1.8/Classes/PHPExcel.php';

        // 设置缓存方式，减少对内存的占用
        $cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_to_phpTemp;
        $cacheSettings = array('cacheTime' => 300, 'memoryCacheSize' => '512MB');
        PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);

        $excel = new PHPExcel();
        $sheet = $excel->setActiveSheetIndex(0);

        $index = 0;
        if ($header)
        {
            foreach ($header as $col => $value)
            {
                $sheet->setCellValue(get_column_index($index, $col), $value);
            }
            ++$index;
        }

        if ($content)
        {
            foreach ($content as $data)
            {
                $col = 0;
                if ($columns)
                {
                    foreach ($columns as $column)
                    {
                        if (isset($column['formatter']))
                        {
                            $value = $column['formatter']($data[$column['db']], $data);
                        }
                        else
                        {
                            $value = $data[$column['db']];
                        }
                        if (Util::is_excel_bigint($value))
                            $sheet->setCellValueExplicit(get_column_index($index, $col), $value);
                        else
                            $sheet->setCellValue(get_column_index($index, $col), $value);
                        ++$col;
                    }
                }
                else
                {
                    foreach ($data as $value)
                    {
                        if (Util::is_excel_bigint($value))
                            $sheet->setCellValueExplicit(get_column_index($index, $col), $value);
                        else
                            $sheet->setCellValue(get_column_index($index, $col), $value);
                        ++$col;
                    }
                }
                ++$index;
            }
        }

        header('pragma:public');
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="' . $filename . '"');
        header('Content-Disposition:attachment;filename=' . $filename);
        $writer = PHPExcel_IOFactory::createWriter($excel, 'Excel5');
        $writer->save('php://output');
    }

    static function format_money($number)
    {
        if ($number >= 0.005) $number -= 0.005;
        return number_format($number, 2, ".", "");
    }
}